package com.itheima.health.service;

import com.itheima.health.mapper.MemberReportMapper;
import com.itheima.health.model.pojos.*;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Service
public  class MemberReportService {
    @Autowired
    private MemberReportMapper memberReportMapper;

    public MemberReportVo getMemberReport() {
        LocalDate lastMonth = LocalDate.now();
        LocalDate startMonth= lastMonth.minusMonths(12);
      List<MemberReport> memberReports= memberReportMapper.getMemberReport(startMonth,lastMonth);
        MemberReportVo memberReportVo = new MemberReportVo();
        List<String> moths=new ArrayList<>();
        List<Integer> memberCount=new ArrayList<>();
        if (!memberReports.isEmpty()){
            for (MemberReport memberReport : memberReports) {
                moths.add(memberReport.getMonth());
                memberCount.add(memberReport.getMemberCount());
            }
            memberReportVo.setMonths(moths);
            memberReportVo.setMemberCount(memberCount);
        }
        return memberReportVo;
    }

    public SetmealReportVo getSetmealReport() {
        String year="";
        List<SetmealCount> setmealCounts=  memberReportMapper.getSetmealCount(year);
        SetmealReportVo setmealReportVo = new SetmealReportVo();
        if (!setmealCounts.isEmpty()){
            List<String> setmealNames=new ArrayList<>();
            for (SetmealCount setmealCount : setmealCounts) {
                setmealNames.add(setmealCount.getName());
            }
            setmealReportVo.setSetmealNames(setmealNames);
            setmealReportVo.setSetmealCount(setmealCounts);
        }
        return setmealReportVo;
    }

    public BusinessReportDataVo getBusinessReportData() {
        BusinessReportDataVo businessReportDataVo = new BusinessReportDataVo();
        //会员数据统计        //获取预约到诊数据统计
        BusinessReportDataVo businessMemberData=  memberReportMapper.getMemberDatasAndOrderDatas();

        //获取全部预约人数
        Integer number =memberReportMapper.getAllOrder();
        //获取套餐信息
        String year = String.valueOf(LocalDate.now().getYear());
        List<SetmealCount> setmealCount = memberReportMapper.getSetmealCount(year);
        List<BusinessReportDataVo.HotSetmeal> hotSetmeals=new ArrayList<>();
        if (!setmealCount.isEmpty()){
            for (SetmealCount count : setmealCount) {
                BusinessReportDataVo.HotSetmeal hotSetmeal = new BusinessReportDataVo.HotSetmeal();
                hotSetmeal.setName(count.getName());
                Integer value = count.getValue();
                hotSetmeal.setSetmeal_count(value);
                hotSetmeal.setProportion(1.0*value/number);
                hotSetmeals.add(hotSetmeal);
            }
        }
        BeanUtils.copyProperties(businessMemberData,businessReportDataVo);
        businessReportDataVo.setHotSetmeal(hotSetmeals);
        businessReportDataVo.setReportDate(LocalDate.now());
        return businessReportDataVo;
    }

    public void exportBusinessReport(HttpServletResponse response,String fileName,BusinessReportDataVo vo) {
        /** 第一步，创建一个Workbook，对应一个Excel文件  */
        HSSFWorkbook wb = new HSSFWorkbook();
        /** 第二步，在Workbook中添加一个sheet,对应Excel文件中的sheet  */
        HSSFSheet sheet = wb.createSheet("运营数据统计");

        /** 第三步，设置样式以及字体样式*/
        HSSFCellStyle contentStyle = createContentCellStyle(wb);
        //		日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //设置全局 单元格  默认 宽度
        sheet.setDefaultColumnWidth(36);
        /** 第四步，创建标题 ,合并标题单元格 */
        // 行号
        int rowNum = 0;
        // 创建第一页的第一行，索引从0开始
        HSSFRow row0 = sheet.createRow(rowNum++);
        HSSFRow row = sheet.createRow(rowNum++);
        row0.setHeight((short) 500);// 设置行高
        row.setHeight((short) 500);

        String title = "运营数据统计";
        HSSFCell c00 = row0.createCell(0);

        c00.setCellValue(title);
        // 合并单元格，参数依次为起始行，结束行，起始列，结束列 （索引0开始）
        CellRangeAddress range = new CellRangeAddress(0, 1, 0, 3); // 标题合并单元格操作，3为总列数
        sheet.addMergedRegion(range);
/*        sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 3));//标题合并单元格操作，3为总列数
        c00.setCellStyle(contentStyle);*/
        // 应用样式到合并区域内的每个单元格
        for (int i = range.getFirstRow(); i <= range.getLastRow(); i++) {
            HSSFRow r = sheet.getRow(i);
            if (r == null) {
                r = sheet.createRow(i);
            }
            for (int j = range.getFirstColumn(); j <= range.getLastColumn(); j++) {
                HSSFCell cell = r.getCell(j);
                if (cell == null) {
                    cell = r.createCell(j);
                }
                cell.setCellStyle(contentStyle);
            }
        }

        // 第二行
        HSSFRow row1 = sheet.createRow(rowNum++);
        row1.setHeight((short) 500);
        for (int i = 0; i < 4; i++) {
            HSSFCell tempCell1 = row1.createCell(i);
            tempCell1.setCellStyle(contentStyle);
            if (i == 0) {
                tempCell1.setCellValue("");
            } else if (i == 1) {
                tempCell1.setCellValue("日期: "+vo.getReportDate());
            } else if(i == 2) {
                tempCell1.setCellValue("");
            }else {
                tempCell1.setCellValue("");
            }
        }



        // 合并
/*        sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 0));
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 1, 1));
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 2, 3));*/

        // 第三行
        HSSFRow row2 = sheet.createRow(rowNum++);
        row2.setHeight((short) 500);
        String title2 = "运营数据统计";
        HSSFCell tempCell2 = row2.createCell(0);
        tempCell2.setCellStyle(contentStyle);
        tempCell2.setCellValue(title2);

        // 合并
        sheet.addMergedRegion(new CellRangeAddress(3, 3, 0, 3));

        // 第四行
        HSSFRow row3 = sheet.createRow(rowNum++);
        row3.setHeight((short) 500);
        for (int i = 0; i < 4; i++) {
            HSSFCell tempCell3 = row3.createCell(i);
            tempCell3.setCellStyle(contentStyle);
            if (i == 0) {
                tempCell3.setCellValue("项目名称： ");
            } else if (i == 1) {
                tempCell3.setCellValue(vo.getTodayNewMember());
            } else if(i == 2) {
                tempCell3.setCellValue("总会员数: ");
            }else {
                tempCell3.setCellValue(vo.getTotalMember());
            }
        }

        // 第五行
        HSSFRow row4 = sheet.createRow(rowNum++);
        row4.setHeight((short) 500);
        for (int i = 0; i < 4; i++) {
            HSSFCell tempCell4 = row4.createCell(i);
            tempCell4.setCellStyle(contentStyle);
            if (i == 0) {
                tempCell4.setCellValue("本周新增会员数： ");
            } else if (i == 1) {
                tempCell4.setCellValue(vo.getThisWeekNewMember());
            } else if(i == 2) {
                tempCell4.setCellValue("本月新增会员数： ");
            }else {
                tempCell4.setCellValue(vo.getThisMonthNewMember());
            }
        }

        // 第六行
        HSSFRow row5 = sheet.createRow(rowNum++);
        row5.setHeight((short) 500);
        String title3 = "预约到诊数据统计";
        HSSFCell tempCell5 = row5.createCell(0);
        tempCell5.setCellStyle(contentStyle);
        tempCell5.setCellValue(title3);

        // 合并
        sheet.addMergedRegion(new CellRangeAddress(6, 6, 0, 3));

        // 第七行
        HSSFRow row6 = sheet.createRow(rowNum++);
        row6.setHeight((short) 500);
        for (int i = 0; i < 4; i++) {
            HSSFCell tempCell6 = row6.createCell(i);
            tempCell6.setCellStyle(contentStyle);
            if (i == 0) {
                tempCell6.setCellValue("今日预约数： ");
            } else if (i == 1) {
                tempCell6.setCellValue(vo.getTodayOrderNumber());
            } else if(i == 2) {
                tempCell6.setCellValue("今日到诊数： ");
            }else {
                tempCell6.setCellValue(vo.getTodayVisitsNumber());
            }
        }

        // 第八行
        HSSFRow row7 = sheet.createRow(rowNum++);
        row7.setHeight((short) 500);
        for (int i = 0; i < 4; i++) {
            HSSFCell tempCell7 = row7.createCell(i);
            tempCell7.setCellStyle(contentStyle);
            if (i == 0) {
                tempCell7.setCellValue("本周预约数： ");
            } else if (i == 1) {
                tempCell7.setCellValue(vo.getThisWeekOrderNumber());
            } else if(i == 2) {
                tempCell7.setCellValue("本周到诊数： ");
            }else {
                tempCell7.setCellValue(vo.getThisWeekVisitsNumber());
            }
        }

        // 第九行
        HSSFRow row8 = sheet.createRow(rowNum++);
        row8.setHeight((short) 500);
        for (int i = 0; i < 4; i++) {
            HSSFCell tempCell8 = row8.createCell(i);
            tempCell8.setCellStyle(contentStyle);
            if (i == 0) {
                tempCell8.setCellValue("本月预约数： ");
            } else if (i == 1) {
                tempCell8.setCellValue(vo.getThisMonthOrderNumber());
            } else if(i == 2) {
                tempCell8.setCellValue("本月到诊数： ");
            }else {
                tempCell8.setCellValue(vo.getThisMonthVisitsNumber());
            }
        }
        // 第十行
        HSSFRow row9 = sheet.createRow(rowNum++);
        row9.setHeight((short) 500);
        String title4 = "预约到诊数据统计";
        HSSFCell tempCell9 = row9.createCell(0);
        tempCell9.setCellStyle(contentStyle);
        tempCell9.setCellValue(title4);
        // 合并
        sheet.addMergedRegion(new CellRangeAddress(10, 10, 0, 3));

        // 第十一行
        HSSFRow row10 = sheet.createRow(rowNum++);
        row10.setHeight((short) 500);
        for (int i = 0; i < 4; i++) {
            HSSFCell tempCell10 = row10.createCell(i);
            tempCell10.setCellStyle(contentStyle);
            if (i == 0) {
                tempCell10.setCellValue("套餐名称");
            } else if (i == 1) {
                tempCell10.setCellValue("预约数量");
            } else if(i == 2) {
                tempCell10.setCellValue("占比");
            }else {
                tempCell10.setCellValue("备注");
            }
        }
        //动态表格
        List<BusinessReportDataVo.HotSetmeal> hotSetmeal = vo.getHotSetmeal();
        for (BusinessReportDataVo.HotSetmeal setmeal : hotSetmeal) {
            HSSFRow tempRow = sheet.createRow(rowNum++);
            tempRow.setHeight((short) 500);
            for (int i = 0; i < 4; i++) {
                HSSFCell tempCell10 = tempRow.createCell(i);
                tempCell10.setCellStyle(contentStyle);
                if (i == 0) {
                    //"套餐名称"
                    tempCell10.setCellValue(setmeal.getName());
                } else if (i == 1) {
                    //"预约数量"
                    tempCell10.setCellValue(setmeal.getSetmeal_count());
                } else if(i == 2) {
                    //"占比"
                    tempCell10.setCellValue(setmeal.getProportion());
                }else {
                    //"备注"
                    tempCell10.setCellValue("");
                }
            }
        }
        try {
            //调用下载     导出
            downloadExcel(response,wb ,fileName+".xls");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //下载
    public static void downloadExcel(HttpServletResponse response, HSSFWorkbook wb , String fileName) throws IOException {
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        fileName="统计分析.xls";
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName).getBytes(), "iso-8859-1"));
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            wb.write(out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    /**
     * 创建内容样式
     * @param wb
     * @return
     */
    private static HSSFCellStyle createContentCellStyle(HSSFWorkbook wb) {
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中
        cellStyle.setWrapText(true);// 设置自动换行
        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
        cellStyle.setBorderLeft(BorderStyle.THIN); //左边框
        cellStyle.setBorderRight(BorderStyle.THIN); //右边框
        cellStyle.setBorderTop(BorderStyle.THIN); //上边框

        // 生成12号字体
        HSSFFont font = wb.createFont();
        font.setColor((short)8);
        font.setFontHeightInPoints((short) 12);
        cellStyle.setFont(font);

        return cellStyle;
    }

}



